/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain.shell;

import tal.drivechain.matchers.VarMatcher;
import tal.drivechain.plugin.Channel;
import tal.drivechain.variable.VarTableListener;
import tal.drivechain.variable.Variable;

/**
 *
 * @author eisental
 */
public class VariableSpy extends Spy implements VarTableListener {
    VarMatcher trigger;

    public void globalMessageEvent(Variable message) {
        if (trigger.matches(message, Channel.GLOBALMESSAGE, null))
            out.println("spy: Global message " + message + " was sent.");
    }

    public void setVarEvent(Variable message) {
        if (trigger.matches(message, Channel.SETVAR, null))
            out.println("spy: Variable " + message.getName() + " was created or changed: " + message);

    }

    public void removeVarEvent(Variable var) {
    }

    public void varScopeChanged(Variable var, boolean isPublic) {
    }

    @Override
    public void setupSpy(String criteria) {
        trigger = new VarMatcher();
        trigger.parsePattern(criteria);
        chain.getVarTable().addListener(this);
    }

    @Override
    public void destroy() {
        chain.getVarTable().removeListener(this);
    }

    @Override
    @SuppressWarnings("empty-statement")

    public String report() {
        String ret = "";
        for (Variable var : chain.getVarTable().values()) {
            if (trigger.matches(var, Channel.CHAIN, chain) ||
                    trigger.matches(var, Channel.GLOBALMESSAGE, chain) ||
                    trigger.matches(var, Channel.SETVAR, chain))
                            ret += var.toString(chain) + ", ";
        }
        if (ret.length()!=0)
            return ret.substring(0, ret.length() - 2);
        else return "Not spying on any variables currently.";
    }

    private static int freeId = 0;

    @Override
    public String getName() {
        return "varspy" + (freeId++);
    }

}
